#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>

#include "lib/MechManiaClient.h"
#include "mm14/Types.h"
#include "Client.h"
#include "State.h"

#include <iostream>

using namespace mm14;
using namespace std;

bool done = false;
void client_tick(State &state)
{
	cout << "Wha?" << endl;
	
    if (!done)
    {
	done = true;
	srand(time(NULL));
	for (unsigned int i = 0; i < 3; ++i)
	{
		Weapon weapon = Weapon();
		weapon.type() = MINER;
		Engine engine = Engine();
		engine.maxSpeed() = 200;
		PowerCore core = PowerCore();
		core.maxPower() = 200;
		core.powerRegen() = 200;
		Hull hull;
		hull.maxHealth() = 12;
		std::vector<mm14::Weapon> weapons;
		weapons.push_back(weapon);
		Ship s = state.BuildShip(engine, hull, core, Sensor(), weapons);
		state.BuyShip(s);
	}
   }
	std::vector<Ship> my_ships = state.GetMyShips();
	bool first = true;
	Ship attacker_ship;
	for (std::vector<Ship>::const_iterator i = my_ships.begin(); i!= my_ships.end(); ++i)
	{
		if (first)
		{
		 	attacker_ship = *i;
			first = false;
		}
		//state.AttackShip(attacker_ship, *i, weapon);
	}
 

	return;
}

int main(int argc, char* argv[])
{
	if (argc < 3)
	{
		std::cout << argv[0] << " ip port" << std::endl;
		return 1;
	}

	std::string ip = argv[1];
	int port = ::atoi(argv[2]);

	Networking::MechManiaClient client = Networking::MechManiaClient();

	client.Connect(ip, port);

	std::string data;

	//std::string username = "(Y (Y Y))";
	//std::string password = "dir62BB#";
	std::string username = "Phobos";
	std::string password = "55wibTH*";

	mm14::GameTurn game_turn;
	game_turn.username() = username;
	game_turn.password() = password;
	std::cerr << mm14::WriteXML(game_turn) << std::endl;
	client.SendTurn(mm14::WriteXML(game_turn));

	while (!(data = client.ReceiveTurn()).empty())
	{
		std::cout << std::setw(10) << std::setfill( '0' ) << data.length() << data;

		mm14::GameState game_state = mm14::ReadXML(data);
		mm14::GameTurn game_turn;

		game_turn.username() = username;
		game_turn.password() = password;

		mm14::State s = mm14::State(game_state, game_turn);
		client_tick(s);

		std::string turn = WriteXML(game_turn);
		std::cerr << std::setw(10) << std::setfill( '0' ) << turn.length() << turn;
		client.SendTurn(mm14::WriteXML(game_turn));
	}

	return 0;
}
